package net.xuele.learn.mytomcat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by GaoQingming on 2019/4/13 0013.
 */
public class MyTomcat {

    int port = 8081;
    private Map<String, String> urlMap = new HashMap<>();

    public MyTomcat(int port) {
        this.port = port;
    }

    public void start() {
        initServletMapping();

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(this.port);
            System.out.println("server started;");

            while (true) {
                Socket accept = serverSocket.accept();
                InputStream inputStream = accept.getInputStream();
                OutputStream outputStream = accept.getOutputStream();

                MyRequest myRequest = new MyRequest(inputStream);
                MyResponse myResponse = new MyResponse(outputStream);

                dispatch(myRequest, myResponse);

                accept.close();
            }
        } catch (Exception e) {

        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void dispatch(MyRequest myRequest, MyResponse myResponse) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        String clazz = urlMap.get(myRequest.getUrl());
        Class<MyServlet> aClass = (Class<MyServlet>) Class.forName(clazz);
        MyServlet myServlet = aClass.newInstance();
        myServlet.service(myRequest, myResponse);
    }

    private void initServletMapping() {
        for (ServletMapping servletMapping : ServletMappingConfig.servletMappingList) {
            urlMap.put(servletMapping.getUrl(), servletMapping.getClazz());
        }

    }

    public static void main(String[] args) {
        new MyTomcat(8081).start();
    }
}
